package com.xjw.hospital.controller;

import cn.hutool.core.thread.ThreadUtil;
import com.xjw.annotation.FXController;
import com.xjw.annotation.FXRedirect;
import com.xjw.annotation.FXWindow;
import com.xjw.coreutil.common.StringUtil;
import com.xjw.entity.FXBaseController;
import com.xjw.hospital.utils.EmailUtil;
import com.xjw.hospital.utils.ToolUtil;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.TextField;
import javafx.scene.text.Text;

/**
 * @author 徐军文
 * @since 2022/8/27 15:24
 */
@FXController(path = "fxml/config.fxml")
@FXWindow(title = "修改配置", icon = "image/icon.png")
public class ConfigController extends FXBaseController {

    @FXML
    private TextField receiverEle;

    @FXML
    private TextField allGetTimeEle;

    @FXML
    private TextField getTimeEle;

    @FXML
    private Text msgEle;

    @Override
    public void onShow() {
        receiverEle.setText(ToolUtil.propUtil.getStr("receiver"));
        allGetTimeEle.setText(ToolUtil.propUtil.getStr("allGetTime"));
        getTimeEle.setText(ToolUtil.propUtil.getStr("getTime"));
    }

    @FXML
    @FXRedirect
    public String saveConfog() {
        ToolUtil.propUtil.setProperty("receiver", receiverEle.getText());
        ToolUtil.propUtil.setProperty("allGetTime", allGetTimeEle.getText());
        ToolUtil.propUtil.setProperty("getTime", getTimeEle.getText());
        ToolUtil.propUtil.store();
        return "MainController";
    }

    @FXML
    @FXRedirect
    public String cancelConfig() {
        return "MainController";
    }

    @FXML
    private void testSendEmail() {
        if (StringUtil.isNotEmpty(receiverEle.getText())) {
            if (EmailUtil.sendEmail("测试邮件", receiverEle.getText())) {
                setMsg("操作成功");
            } else {
                setMsg("操作失败");
            }
        } else {
            setMsg("请设置邮件地址");
        }
    }

    private void setMsg(String msg) {
        ThreadUtil.execAsync(() -> Platform.runLater(() -> {
            msgEle.setText(msg);
            ThreadUtil.safeSleep(3000L);
            msgEle.setText("");
        }));
    }
}
